// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/connectors/hive/file_handle.h>

#include <gtest/gtest.h>
#include <pollux/common/caching/simple_lru_cache.h>
#include <pollux/common/file/file.h>
#include <pollux/common/file/file_systems.h>
#include <pollux/common/file/temp_file_path.h>

using namespace kumo::pollux;

TEST(FileHandleTest, localFile) {
  filesystems::registerLocalFileSystem();

  auto tempFile = exec::test::TempFilePath::create();
  const auto& filename = tempFile->getPath();
  remove(filename.c_str());

  {
    LocalWriteFile writeFile(filename);
    writeFile.append("foo");
  }

  FileHandleFactory factory(
      std::make_unique<SimpleLRUCache<std::string, FileHandle>>(1000),
      std::make_unique<FileHandleGenerator>());
  auto fileHandle = factory.generate(filename);
  ASSERT_EQ(fileHandle->file->size(), 3);
  char buffer[3];
  ASSERT_EQ(fileHandle->file->pread(0, 3, &buffer), "foo");

  // Clean up
  remove(filename.c_str());
}

TEST(FileHandleTest, localFileWithProperties) {
  filesystems::registerLocalFileSystem();

  auto tempFile = exec::test::TempFilePath::create();
  const auto& filename = tempFile->getPath();
  remove(filename.c_str());

  {
    LocalWriteFile writeFile(filename);
    writeFile.append("foo");
  }

  FileHandleFactory factory(
      std::make_unique<SimpleLRUCache<std::string, FileHandle>>(1000),
      std::make_unique<FileHandleGenerator>());
  FileProperties properties = {
      .fileSize = tempFile->fileSize(),
      .modificationTime = tempFile->fileModifiedTime()};
  auto fileHandle = factory.generate(filename, &properties);
  ASSERT_EQ(fileHandle->file->size(), 3);
  char buffer[3];
  ASSERT_EQ(fileHandle->file->pread(0, 3, &buffer), "foo");

  // Clean up
  remove(filename.c_str());
}
